<template>
  <div class="app-container">
    <el-dialog :title="dialogTitle" :destroy-on-close="true" :visible.sync="importOpen" width="75%" append-to-body :close-on-press-escape="false" :close-on-click-modal="false" :before-close="close" class="app-container-compactness">

      <el-row style="margin: 10px 0;">
        <el-col :span="24">
          <el-card shadow="always">
            <div style="display: flex;justify-content: space-around;">
              <!--              <span><span style="font-weight: bold;">商品名称：</span>{{ form.goods_Cname }}</span>-->
              <span><span style="font-weight: bold;">料号：</span>{{ form.goods_name }}</span>
              <span><span style="font-weight: bold;">托盘数：</span>{{ table_tray_num }}</span>
              <span><span style="font-weight: bold;">包装：</span>{{ form.packing_num }}/{{ form.unit_name }}</span>
              <span><span style="font-weight: bold;">要求数量/表格数量：</span> {{ total_number }}/
                <span v-if="table_total_num > total_number" style="color: red;">{{ table_total_num }}（超出）</span>
                <span v-else>{{ table_total_num }}</span>
              </span>

            </div>
          </el-card>

        </el-col>
      </el-row>
      <el-collapse-transition>

        <upload-excel-component v-show="uploadRadio == 1" style="margin-bottom: 12px;" :on-success="handleSuccess" :before-upload="beforeUpload" />

      </el-collapse-transition>
      <div class="btn-box">

        <div class="btn-left">
          <el-button icon="el-icon-upload2" type="danger" :disabled="!multipleSelection.length" @click="uploadData">选中上传</el-button>
          <el-button icon="el-icon-delete" style="margin-left: 0" type="warning" :disabled="!multipleSelection.length" @click="deleteChecked">删除选中</el-button>
          <!--          <el-button icon="el-icon-milk-tea" style="margin-left: 0" type="warning" @click="clearAllSuccess">清空已成功</el-button>-->
        </div>
        <div class="btn-middle">
          <el-tooltip :content="'仅在数据无修改情况下系统预分配'" placement="top">
            <el-switch
              v-if="importOpen"
              v-model="btnMiddleValue"
              :active-value="true"
              :inactive-value="false"
              active-text="系统预分配"
              inactive-text=""
              :disabled="!support_yfp"
              @change="conversionFunc($event)"
            />
          </el-tooltip>
        </div>
        <div class="btn-right">
          <el-button type="primary" style="margin-left: 0" icon="el-icon-plus" @click="insertEvent()">头部插入</el-button>
          <el-button type="danger" style="margin-left: 0" icon="el-icon-plus" @click="insertEvent(-1)">尾部插入</el-button>
        </div>
        <!--      <el-button @click="validAllEvent">整个表格校验</el-button>-->
        <!--      <el-button @click="fullValidEvent">校验</el-button>-->
      </div>

      <ux-grid
        ref="plxTable"
        v-loading="dialogLoading"
        :cell-style="{height:'24px'}"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :element-loading-text="loadingText"
        size="mini"
        border
        :show-summary="true"
        :show-overflow="'title'"
        :show-header-overflow="'title'"
        keep-source
        stripe
        :rules="rules"
        height="500"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        :checkbox-config="{checkMethod: selectable, highlight: true}"
        @selection-change="handleSelectionChange"
      >
        <ux-table-column type="checkbox" width="60" />
        <ux-table-column type="index" title="行号" width="80" />

        <ux-table-column resizable prop="tray_id" width="200px" :edit-render="{autofocus: '.el-input__inner'}" field="tray_id" title="托盘码">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.tray_id" />
          </template>
          <template v-slot="{ row }">{{ row.tray_id }}</template>
        </ux-table-column>

        <ux-table-column prop="number" :edit-render="{autofocus: '.el-input__inner'}" field="number" title="数量*">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.number" @change="changeTableRowNumber(scope.row,$event)" />
          </template>
          <template v-slot="{ row }">{{ row.number }}</template>
        </ux-table-column>

        <ux-table-column prop="box_number" :edit-render="{autofocus: '.el-input__inner'}" field="box_number" title="箱数*">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.box_number" />
          </template>
          <template v-slot="{ row }">{{ row.box_number }}</template>
        </ux-table-column>

        <ux-table-column field="goods_status" title="状态*" prop="goods_status" :edit-render="{autofocus: '.el-input__inner'}">
          <template v-slot:edit="scope">
            <el-select v-model="scope.row.goods_status" filterable @change="$refs.plxTable.updateStatus(scope)">
              <el-option label="Good" value="Good" />
              <el-option label="NG" value="NG" />
              <el-option label="Hold" value="Hold" />
            </el-select>
          </template>
          <template v-slot="{ row }">{{ status_label( row) }}</template>
        </ux-table-column>

        <ux-table-column resizable field="config_id" width="200px" title="库位*" :edit-render="{autofocus: '.el-input__inner'}">
          <template slot="header" slot-scope="scope">
            <div>库位*
              <el-button v-if="distributionConfigNameBtn" :disabled="currentKFPNum <= 0" size="mini" type="primary" style="margin-left: 10px;" @click="FPKKW">分配空库位</el-button>
            </div>
          </template>
          <template v-slot:edit="scope">
            <el-select v-model="scope.row.config_id" filterable style="width: 100%;" @change="changeConfigName(scope)">
              <el-option
                v-for="(item,index) in config_options"
                :key="index"
                :label="item.name"
                :value="item.config_id"
              />
            </el-select>
          </template>
          <template v-slot="{ row }"><span v-html="config_name_label(row)" /></template>
        </ux-table-column>

        <ux-table-column prop="LOT1" :edit-render="{autofocus: '.el-input__inner'}" field="LOT1" title="LOT1">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.LOT1" />
          </template>
          <template v-slot="{ row }">{{ row.LOT1 }}</template>
        </ux-table-column>

        <ux-table-column prop="LOT2" :edit-render="{autofocus: '.el-input__inner'}" field="LOT2" title="LOT2">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.LOT2" />
          </template>
          <template v-slot="{ row }">{{ row.LOT2 }}</template>
        </ux-table-column>

        <ux-table-column prop="LOT3" :edit-render="{autofocus: '.el-input__inner'}" field="LOT3" title="LOT3">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.LOT3" />
          </template>
          <template v-slot="{ row }">{{ row.LOT3 }}</template>
        </ux-table-column>

        <ux-table-column
          align="center"
          width="80"
          fixed="right"
        >
          <template slot="header" slot-scope="scope">
            <span style="color: #67C23A;">操作</span>
          </template>
          <template v-slot="{ row }">
            <i class="el-icon-copy-document" style="font-weight: 1000;" @click="copyRow(row)" />
            <i class="el-icon-delete" style="margin-left: 5px; color: red;font-weight: 1000;" @click="delRow(row)" />
          </template>
        </ux-table-column>

        <!--      <ux-table-column-->
        <!--        title="操作"-->
        <!--        width="200"-->
        <!--        fixed="right"-->
        <!--      >-->
        <!--        <template v-slot="{ row }">-->
        <!--          &lt;!&ndash;判断行是否激活了, 编辑按钮执行的方式就是为了去激活&ndash;&gt;-->
        <!--          <template v-if="$refs.plxTable.isActiveByRow(row)">-->
        <!--            <el-button type="primary" @click="saveEvent(row)">保存</el-button>-->
        <!--            <el-button @click="cancelRowEvent(row)">取消</el-button>-->
        <!--          </template>-->
        <!--          <template v-else>-->
        <!--            <el-button @click="editRowEvent(row)">编辑</el-button>-->
        <!--          </template>-->
        <!--        </template>-->
        <!--      </ux-table-column>-->
      </ux-grid>

      <div style="margin:5px 0; display: flex;justify-content: space-between">
        <div v-if="currentConfigAreaInfoLoading">
          数据计算中<i class="el-icon-loading" />
        </div>
        <div v-else>
          仓库空库位：<span style="color:#409EFF;font-weight: 700; ">{{ emptyConfigNum }} </span>
          /
          未分配数量：<span style="color:#F56C6C;font-weight: 700; ">{{ currentKFPNum }} </span>

        </div>

        <div>
          <el-radio v-model="uploadRadio" label="1" @input="toggleUploadRadio">显示上传组件</el-radio>
          <el-radio v-model="uploadRadio" label="2" @input="toggleUploadRadio">隐藏</el-radio>
        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getConversionList, getProject, traySurplus, getConfigLevel3 } from '@/api/storehouse'
import { providerList } from '@/api/basics'
import { att, createAdd, locationBatchCreate, locationSearchNum, seatList } from '@/api/stock'
export default {
  name: 'SeatImport',
  components: { UploadExcelComponent },
  props: {
    importOpen: {
      type: Boolean,
      default: false
    },
    dialogTitle: {
      type: String,
      default: ''
    },
    warehousingSonId: {
      type: [String, Number, Boolean],
      default: ''
    },
    form: {
      type: [String, Number, Boolean, Object],
      default: null
    }
  },
  data() {
    const projectClientRules = ({ cellValue, rule }) => {
      if (!Array.isArray(cellValue) || cellValue.length != 2) {
        return new Error('请选择项目和委托方')
      }
    }
    return {
      total_number: 0,
      uploadRadio: '2',
      loadingText: '',
      btnMiddleValue: false,
      dialogLoading: false,
      clientParams: {
        page: 1,
        limit: 9999,
        account_code: undefined,
        account_name: undefined
      },
      support_yfp: true,
      config_options: [],
      clientList: [],
      ConversionList: [],
      selectList: [],
      multipleSelection: [],
      err_xid_arr: [],
      selectData: [],
      tableKeyMap: {
        '托盘码': 'tray_id',
        '数量*': 'number',
        '箱数*': 'box_number',
        '状态*': 'goods_status',
        '库位': 'config_id',
        'LOT1': 'LOT1',
        'LOT2': 'LOT2',
        'LOT3': 'LOT3'
      },
      rules: {
        goods_status: [
          // { required: true, validator: projectClientRules, message: '请选择项目和委托方' }
          { required: true, message: '货物状态不能为空' }
        ],
        number: [
          { required: true, message: '商品数量不能为空' }
        ],
        box_number: [
          { required: true, message: '箱数不能为空' }
        ],
        config_id: [
          { required: true, message: '库位不能为空' }
        ]
      },
      tableHeader: [],
      tableData: [],
      columns: [],
      currentConfigAreaInfo: {},
      currentConfigAreaInfoLoading: true
    }
  },
  computed: {
    // 判断托盘码ID是否唯一 不唯一 返回false
    checkTrayIdUnique() {
      const notEmptyArr = this.multipleSelection.filter(item => item.tray_id != '')
      const tray_ids = []
      let result = true
      notEmptyArr.forEach(item => {
        const find = tray_ids.find(id => id === item.tray_id)
        if (!find) {
          tray_ids.push(item.tray_id)
        } else {
          result = false
        }
      })

      return result
    },
    currentKFPNum() {
      if (!this.tableData.length) return this.emptyConfigNum

      const config_id = this.tableData.filter(item => {
        return (item.config_id !== undefined && item.config_id !== null && item.config_id !== '')
      }).map(item => item.config_id) // 所有库位ID

      // 有用的，并且分配了 并且是空的
      const allConfigAreaIds = this.currentConfigAreaInfo.data.filter(item => {
        return config_id.includes(item.config_id) && item.stock === 0
      })

      return this.emptyConfigNum - allConfigAreaIds.length
    },
    emptyConfigNum() {
      if (this.currentConfigAreaInfo.data === undefined || !this.currentConfigAreaInfo.data.length) return 0

      const allConfigAreaIds = this.currentConfigAreaInfo.data.map(item => item.config_id)
      const _selfConfigIds = this.config_options.map(item => item.config_id)

      const intersection = allConfigAreaIds.filter(value => _selfConfigIds.includes(value))

      return this.currentConfigAreaInfo.data.filter(item => {
        return item.stock === 0 && intersection.includes(item.config_id)
      }).length
    },
    distributionConfigNameBtn() {
      if (!this.tableData.length) return false
      const emptyConfigNameArr = this.tableData.filter(item => item.config_id == undefined || item.config_id == null || item.config_id == '')

      if (this.emptyConfigNum === 0) return false

      if (emptyConfigNameArr.length === 0) return false

      return true
    },
    table_total_num() {
      return this.tableData.reduce((total, item) => {
        if (item.hasOwnProperty('number') && item.number !== '') {
          return total + parseInt(item.number)
        } else {
          return total
        }
      }, 0)
    },
    residue() {
      return this.total_number - 0
    },
    table_tray_num() {
      return this.tableData.length
    },
    multipleSelectionNumber() {
      return this.multipleSelection.reduce((total, item) => {
        if (item.hasOwnProperty('number') && item.number !== '') {
          return total + parseInt(item.number)
        } else {
          return total
        }
      }, 0)
    }
  },
  watch: {
    'importOpen': {
      deep: true,
      immediate: true,
      handler: function(newValue, oldValue) {
        console.log(newValue)
        if (newValue === true) {
          this.loadData()
        }
      }
    }
  },
  created() {
    this.project()
    // this.loadData()
    this.seatListFunc()
  },
  mounted() {
    this.getClientList()
  },
  methods: {
    // 分配空库位
    FPKKW() {
      const _selfConfigIds = this.config_options.map(item => item.config_id)
      const table_config_id = this.tableData.map(item => item.config_id)
      // 找到所有未被分配的空库位
      const can_used = this.currentConfigAreaInfo.data.filter(item => {
        return (item.stock === 0 && !table_config_id.includes(item.config_id) && _selfConfigIds.includes(item.config_id))
      })
      if (!can_used.length) return false
      // 找到所有空库位的行
      let i = 0
      console.log('can_user', can_used)
      this.tableData.forEach(item => {
        if (item.config_id === undefined || item.config_id === null || item.config_id === '') { // 需要分配的行
          this.$set(item, 'config_id', can_used[i]['config_id'])
          // item.config_id = can_used[i]['config_id']
          ++i
          if (i > can_used.length) {
            return
          }
        }
      })
      this.$refs.plxTable.loadData(this.tableData)
    },
    seatListFunc() {
      seatList({ id: this.form.checked_config[1], parent_id: this.form.config_parent_info['parent_id'], name: this.form.config_parent_info['name'] }).then(response => {
        if (response.code === 10000) {
          this.currentConfigAreaInfoLoading = false
          this.currentConfigAreaInfo = response.data
        }
      })
    },
    async changeConfigName(scope) {
      await this.$refs.plxTable.updateStatus(scope)
      const { data: { total }} = await locationSearchNum(scope.row.config_id)
      // console.log(total)
      if (total > 0) {
        const result = this.config_options.find(item => item.config_id === scope.row.config_id)
        result.stock = total
        this.$notify.warning({
          title: '提醒',
          message: `当前${result.name}库位存在货物`,
          duration: 0
        })
      }
    },
    delRow(row) {
      this.tableData = this.tableData.filter(item => item._XID !== row._XID)
      this.$refs.plxTable.loadData(this.tableData)
    },
    copyRow(row) {
      const obj = {
        'tray_id': row.tray_id,
        'number': row.number,
        'box_number': row.box_number,
        'goods_status': row.goods_status,
        'config_id': row.config_id,
        'LOT1': row.LOT1,
        'LOT2': row.LOT2,
        'LOT3': row.LOT3
      }
      this.tableData.push(obj)
      this.$refs.plxTable.loadData(this.tableData)
    },
    changeTableRowNumber(row, event) {
      const item = this.tableData.find(obj => obj._XID === row._XID)
      if (isNaN(row.number) || row.number <= 0) {
        item.number = ''
      } else {
        item.number = parseInt(item.number)
      }
    },
    toggleUploadRadio(val) {

    },
    loadData() {
      if (this.form.warehousing_son_id == undefined) {
        return
      }

      getConfigLevel3(this.form.id).then((res) => {
        this.config_options = res.data
      })

      traySurplus({ warehousing_son_id: this.form.warehousing_son_id }).then((res) => {
        this.packing_num = res.data.packing_num
        this.total_number = res.data.total_number
      })
      this.dialogLoading = true
      this.loadingText = '疯狂加载中...'
      getConversionList({
        warehousing_id: this.form.warehousing_id,
        warehousing_son_id: this.form.warehousing_son_id
      }).then((res) => {
        this.ConversionList = [...res.data.tray_info]
        this.support_yfp = res.data.support_yfp !== false

        if (this.ConversionList.length && res.data.support_yfp === false) {
          this.loadingText = '数据正在加载到表格...'
          const conversionNewArr = []
          this.ConversionList.forEach(item => {
            const obj1 = {
              config_id: item.config2,
              goods_status: item.goods_status,
              number: item.number,
              box_number: item.box_number,
              tray_id: item.tray_id,
              configData2: item.configData2,
              LOT1: item.LOT1,
              LOT2: item.LOT2,
              LOT3: item.LOT3
            }
            if (undefined !== item.id) {
              obj1.id = item.id
            }
            conversionNewArr.push(obj1)
          })
          this.tableData = conversionNewArr
          this.$refs.plxTable.loadData(this.tableData)
          this.dialogLoading = false
          return this.$notify.success({
            title: '提示',
            message: `数据加载成功，共计${this.tableData.length}条数据。`
          })
        }

        this.dialogLoading = false
      })
    },
    async conversionFunc(val) {
      if (val) {
        this.dialogLoading = true
        this.loadingText = '系统预分配中...'
        const res = await getConversionList({
          warehousing_id: this.form.warehousing_id,
          warehousing_son_id: this.form.warehousing_son_id
        })
        this.ConversionList = [...res.data.tray_info]
        this.support_yfp = res.data.support_yfp !== false

        if (!this.ConversionList.length) {
          this.dialogLoading = false
          return this.$notify.info({
            title: '提示',
            message: `系统分配数据为空`
          })
        } else {
          const conversionNewArr = []
          this.ConversionList.forEach(item => {
            const obj1 = {
              config_id: item.config2,
              goods_status: item.goods_status,
              number: item.number,
              box_number: item.box_number,
              tray_id: item.tray_id,
              configData2: item.configData2
            }
            if (undefined !== item.id) {
              obj1.id = item.id
            }
            conversionNewArr.push(obj1)
          })
          this.tableData = conversionNewArr
          this.$refs.plxTable.loadData(this.tableData)
          this.dialogLoading = false
          return this.$notify.success({
            title: '提示',
            message: `系统预分配成功，共计${this.tableData.length}条数据。`
          })
        }
      } else {
        this.tableData = []
        this.$refs.plxTable.loadData(this.tableData)
        return this.$notify.success({
          title: '提示',
          message: `预分配数据清除完成。`
        })
      }
    },
    surplusGoods(val, row) {
      this.loadings = true
      // 剩余商品入库数量
      traySurplus({ warehousing_son_id: this.warehousingSonId }).then(response => {
        if (response.code === 10000) {
          this.surplus = response.data.number
          this.packing_num = response.data.packing_num
        }
      })
    },
    clearAllSuccess() {
      this.tableData = this.tableData.filter(item => item.isUpload !== 1)
      this.$refs.plxTable.loadData(this.tableData)
    },
    selectable({ row }) {
      return row.disabled !== 'disabled'
    },
    // 添加插入行
    insertEvent(row) {
      if (row === -1) {
        this.tableData.push({})
      } else {
        this.tableData.unshift({})
      }
      this.$refs.plxTable.loadData(this.tableData)
      // this.$refs.plxTable.reloadData(this.tableData)
    },
    // 删除选中行
    deleteChecked() {
      this.$refs.plxTable.removeCheckboxRow()
      const xids = this.multipleSelection.map(item => item._XID)
      this.tableData = this.tableData.filter(item => !xids.includes(item._XID))
      this.$refs.plxTable.loadData(this.tableData)
      // this.$refs.plxTable.reloadData(this.tableData)
      this.multipleSelection = []
    },
    close() {
      this.tableData = []
      this.multipleSelection = []
      this.btnMiddleValue = false
      this.$emit('update:importOpen', false)
      this.dialogLoading = false
    },
    getClientList() {
      providerList(this.clientParams).then(response => {
        if (response.code === 10000) {
          this.clientList = response.data
        }
      })
      att().then((response) => {
        if (response.code === 10000) {
          this.selectList = JSON.parse(JSON.stringify(response.data))
        }
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async processBatch(startIndex, batchSize) {
      // 计算结束索引
      const endIndex = Math.min(startIndex + batchSize, this.multipleSelection.length)

      const requestData = this.multipleSelection.slice(startIndex, endIndex)
      const requestDataXIDs = requestData.map(item => item._XID)

      requestData.forEach(item => {
        item.isstatus = item.isstatus === '启用' ? 1 : 0
        item.parent_id = this.confidId
      })

      const { data: errArr } = await locationBatchCreate({ list: requestData })
      const errArrKeys = Object.keys(errArr)

      if (errArrKeys) {
        this.tableData.forEach(item => {
          if (requestDataXIDs.includes(item._XID)) {
            if (errArrKeys.includes(item._XID)) {
              item.isUpload = 0
              item.errMsg = errArr[item._XID].errMsg
            } else {
              item.isUpload = 1
              item.disabled = 'disabled'
            }
          }
        })

        this.err_xid_arr = this.err_xid_arr.concat(errArrKeys)
      }

      // 检查是否还有剩余数据需要处理
      if (endIndex < this.multipleSelection.length) {
        // 使用延迟执行来等待一段时间后继续处理下一批数据'
        await new Promise(resolve => setTimeout(resolve, 100))
        await this.processBatch(endIndex, batchSize)
      } else {
        this.multipleSelection = this.multipleSelection.filter(item => this.err_xid_arr.includes(item._XID))
        this.$refs.plxTable.clearSelection()
      }
    },
    async uploadData() {
      const data = await this.$refs.plxTable.validate(this.multipleSelection)

      // 表单校验
      if (data) { // 失败
        let masStr = ''
        Object.values(data).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              masStr += `<p>第 ${rowIndex + 1} 行 ：${rule.message}</p>`
            })
          })
        })
        // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
        return this.$notify.error({
          title: '错误',
          dangerouslyUseHTMLString: true,
          message: masStr,
          duration: 3500
        })
      }
      // 数量校验
      // console.log(this.multipleSelection)
      if (this.multipleSelectionNumber !== this.total_number) {
        return this.$alert(`要求总数量${this.total_number}，当前选中数量${this.multipleSelectionNumber}`, '上传数量和总数量不一致', {
          confirmButtonText: '知道了',
          type: 'error'
        })
      }

      // 托盘码是否重复校验
      if (!this.checkTrayIdUnique) {
        this.$notify({
          type: 'error',
          message: '托盘码重复'
        })
        return false
      }

      // 组装数据-调用接口
      const that = this
      const warehousing = { warehousing_id: that.form.warehousing_id, warehousing_son_id: that.form.warehousing_son_id }
      const goods_info = { goods_id: that.form.goods_id, packing_num: that.form.packing_num }
      createAdd({ list: this.multipleSelection, warehousing: warehousing, goods_info: goods_info }).then(response => {
        if (response.code === 10000) {
          this.$router.push({
            path: '/storehouse/tray',
            query: { warehousing_id: this.form.warehousing_id, warehousing_son_id: this.form.warehousing_son_id, page_date: new Date().getTime()
            }
          })
        }
        this.$emit('update:importOpen', false)
      })

      // console.log(this.$refs.plxTable.getRowById('row_15'))
      // 调用接口
    },
    // 校验
    fullValidEvent() {
      // fullValidate完整校验，和 validate 的区别就是会给每一行进行校验
      this.$refs.plxTable.fullValidate().then(data => {
        // data就是当前检验不通过的
        if (data) {
          let masStr = ''
          Object.values(data).forEach(errList => {
            console.log(errList)
            errList.forEach(params => {
              const { rowIndex, column, rules } = params
              rules.forEach(rule => {
                masStr += `<p>第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}</p>`
              })
            })
          })
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$notify.error({
            title: '错误',
            dangerouslyUseHTMLString: true,
            message: masStr,
            duration: 1500
          })
        } else {
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: 1500
          })
        }
      })
    },
    // 整个表格校验
    validAllEvent() {
      // 1. validate方法 如果你传入一个true， 那么就代表整个表格校验！
      // 2.快速校验，如果存在校验不通过的行，则返回不再继续校验
      this.$refs.plxTable.validate(true).then(data => {
        if (data) {
          this.$message({
            message: '校验不通过',
            type: 'error',
            duration: '1000'
          })
        } else {
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: '1000'
          })
        }
      })
    },
    editRowEvent(row) {
      this.$refs.plxTable.setActiveRow(row)
    },
    consignee_label(row) {
      let label = ''
      this.clientList.forEach(item => {
        if (item.serial_number == row.consignee_serial_number) {
          label = item.account_name
        }
      })
      return label
    },
    status_label(row) {
      return row.goods_status
    },
    config_name_label(row) {
      let label = ''
      this.config_options.forEach(item => {
        if (item.config_id === row.config_id) {
          label = item.name
        }
      })
      // const result = this.config_options.find(item => item.config_id === row.config_id)
      // if (result) {
      //   if (undefined === result.stock) {
      //     label = result.name
      //   } else {
      //     label = `<span style="color:red;font-weight: 1000;">${result.name}</span><span style="color: red;font-weight: 700;">【货物数${result.stock}】</span>`
      //   }
      // }

      if (label == '' && row.configData2) {
        row.configData2.forEach(itm => {
          if (itm.config_id == row.config_id) {
            label = `<span style="color:red;font-weight: 1000;">${itm.name}</span><span style="color: blue;font-weight: 700;">【该库位属其他库区】</span>`
          }
        })
      }
      return label
    },
    project_client_label(row) {
      let label = ''
      this.selectData.forEach(item => {
        if (Array.isArray(row.project_client) && item.value == row.project_client[0]) {
          item.children.forEach(itm => {
            if (itm.value == row.project_client[1]) {
              label = item.label + '/' + itm.label
              return
            }
          })
        }
      })
      return label
    },
    project() {
      const that = this
      getProject().then(response => {
        if (response.code === 10000) {
          that.selectData = response.data
        }
      })
    },
    // 点击保存
    saveEvent(row) {
      // 判断是否发生改变
      console.log(this.$refs.plxTable.isUpdateByRow(row))
      if (this.$refs.plxTable.isUpdateByRow(row)) {
        // 局部保存，并将行数据恢复到初始状态（如果 第二个参数record 为空则不改动行数据，只恢复状态）
        // 必须执行这个，不然下次点击保存，还是保存成功哦！状态没改变哦
        this.$refs.plxTable.reloadRow(row, null, null)
        // ...保存逻辑相关（后端呀，或者前端呀）
        this.$message({
          message: '恭喜你，保存成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '保存失败，你没改变当前行的数据',
          type: 'error'
        })
      }
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.multipleSelection = []
      this.tableData = results
      const that = this

      const newData = this.tableData.map(item => {
        const newItem = {}
        for (const key in item) {
          if (Object.prototype.hasOwnProperty.call(that.tableKeyMap, key)) {
            newItem[that.tableKeyMap[key] || key] = item[key]
          }
        }
        return newItem
      })
      this.tableData = newData

      this.tableData.forEach(item => {
        // 商品状态
        if (item.goods_status) {
          const goods_status_options = ['Good', 'Hold', 'NG']
          if (!goods_status_options.includes(item.goods_status)) {
            item.goods_status = ''
          }
        }

        // 库位
        if (item.config_id) {
          const find_config = this.config_options.find(itm => itm.name === item.config_id)

          if (undefined === find_config) { // 没找到
            item.config_id = ''
          } else {
            item.config_id = find_config.config_id
          }
        }
      })

      this.uploadRadio = '2'
      this.tableHeader = header
      this.$refs.plxTable.reloadData(this.tableData)
    }
  }
}
</script>
<style lang="less" scoped>
.btn-box{
  display: flex;
  justify-content: space-between;
}
/deep/ .el-dialog__body{
  padding-top: 0 !important;
}
</style>
